<template>
  <!-- 当数据加载中时显示骨架屏 -->
  <BlogSkeleton v-if="loading" />

  <!-- 当数据加载完成后显示实际内容 -->
  <div class="blog-detail" v-else>
    <!-- 左边菜单 -->
    <aside class="blog-sidebar">
      <div class="sidebar-section">
        <div class="sidebar-title">FIT & CARE</div>
      </div>
      <div class="sidebar-section">
        <div class="sidebar-subtitle">CATEGORIES</div>
        <div class="sidebar-divider"></div>
        <ul class="sidebar-categories">
          <li v-for="(item, index) in menuList" :key="item.id" @click="handleMenu(item, index)">
            <div class="sidebar-category-item-name">
              <div :class="{ active: tabIndex === item.id }">
                {{ item.name }}
              </div>
              <div v-if="item.children?.length > 0 && item.showChildren">
                <ul class="sidebar-category-children">
                  <li v-for="child in item.children" :key="child.id" @click.stop="handleChildMenu(child, index)"
                    :class="{ active: tabIndexChild === child.id }">
                    <!-- 鼠标悬浮显示全部内容 -->
                    <a-tooltip>
                      <template #title>{{ child.title }}</template>
                      {{ child.title }}
                    </a-tooltip>
                  </li>
                </ul>
              </div>
            </div>
            <div class="sidebar-category-item-icon">
              <RightOutlined v-if="!item.showChildren" />
              <DownOutlined v-else />
            </div>
          </li>

        </ul>
      </div>
      <!-- 最近文章 -->
      <div class="sidebar-section">
        <div class="sidebar-subtitle">RECENT POST</div>
        <div class="sidebar-divider"></div>
        <ul class="sidebar-posts">
          <li v-for="(item, index) in articleList" :key="item.id">
            <div class="post-title" @click="handleChildMenu(item, index)">{{ item.title }}</div>
            <div class="post-date">{{ item.published_at }}</div>
          </li>
        </ul>
      </div>
    </aside>
    <!-- 右边详情内容 -->
    <div style="width: 920px;">
      <!-- 右侧内容骨架屏 -->
      <div v-if="contentLoading" class="right-content-skeleton">
        <a-skeleton :paragraph="{ rows: 1 }" active />
        <a-skeleton :paragraph="{ rows: 10 }" active />
        <a-skeleton :paragraph="{ rows: 1 }" active />
      </div>
      <!-- 右侧实际内容 -->
      <div v-else-if="contentData && contentData.title">
        <div class="right-title">{{ contentData.title }}</div>
        <div class="right-date">{{ contentData.published_at }}</div>
        <div v-html="renderedContent" class="markdown-body"></div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { getnewList, getdetail, getnav, getnavList } from "@/api/blog"
import { ref, computed, onMounted } from 'vue';
import { RightOutlined, DownOutlined } from '@ant-design/icons-vue';
import { useRoute } from 'vue-router';
import MarkdownIt from 'markdown-it'
import BlogSkeleton from './BlogSkeleton.vue';

// 定义类型
interface BlogItem {
  id: number;
  name: string;
  title?: string;
  published_at?: string;
  [key: string]: any;
}

interface BlogContent {
  id?: number;
  title?: string;
  published_at?: string;
  content?: string;
  [key: string]: any;
}

onMounted(async () => {
  if (route.query.id) {
    tabIndex.value = Number(route.query.id);
  }
  if (route.query.childId) {
    tabIndexChild.value = Number(route.query.childId);
  }

  // 初始化数据
  getAticleList();
  await getMenuList();
})

// 加载状态
const loading = ref(true);
const contentLoading = ref(false);
const route = useRoute()
const md = new MarkdownIt({
  html: true,
  breaks: true,
  linkify: true,
  typographer: true
})
// 左侧菜单列表
const menuList = ref<BlogItem[]>([]);
// 近期文章
const articleList = ref<BlogItem[]>([]);
const tabIndex = ref<number>(0);

// 点击左侧分类菜单
const handleMenu = (item: BlogItem, index?: number) => {
  // 当前showChildren为true时，其他showChildren都为false
  menuList.value.forEach((m) => {
    if (m.id !== item.id) {
      m.showChildren = false;
    }
  });
  if (item.showChildren) {
    item.showChildren = false;
  } else {
    item.showChildren = true;
  }

  if (index !== undefined && index >= 0) {
    tabIndex.value = item.id;
  }
  getSecondMenuList(item, true);
}
const tabIndexChild = ref<number>(0);
const handleChildMenu = (item: BlogItem, index: number) => {
  tabIndexChild.value = item.id;
  getDetailData(item.id);
}

// 获取博客二级菜单
const getSecondMenuList = async (item: BlogItem, isFirst: boolean = false) => {
  const res = await getnavList(item.id);
  if (res.code === 200) {
    if (res.data?.length > 0) {
      item.children = res.data[0].list;
      // 如果是从博客首页首次进来存在路由ID参数，则使用它； 但是如果点击了左侧一级导航需要选中子导航的第一个
      if (item.children.length > 0 && (!route.query.childId || isFirst) ) {
        getDetailData(item.children[0].id);
        tabIndexChild.value = item.children[0].id;
      }
    }
  }
}

// 获取最近文章
const getAticleList = async () => {
  try {
    const res = await getnewList();
    if (res.code === 200) {
      articleList.value = res.data;
    }
  } catch (error) {
    console.error('Error fetching article list:', error);
  }
}

// 获取博客列表
const getMenuList = async () => {
  try {
    const res = await getnav();
    if (res.code === 200) {
      menuList.value = res.data;

      menuList.value.forEach(async (item) => {
        if (item.id === Number(route.query.id)) {
          item.showChildren = true;
          await getSecondMenuList(item);
        }
      });

      if (route.query.childId) {
        await getDetailData(Number(route.query.childId));
      } else {
        // 如果存在路由ID参数，则使用它；否则默认选中第一个
        if (menuList.value.length > 0) {
          tabIndex.value = menuList.value[0]?.id || 0;
          if (menuList.value[0]?.id) {
            getDetailData(menuList.value[0].id);
          }
        }
      }
    }
  } catch (error) {
    console.error('Error fetching menu list:', error);
  } finally {
    // 所有初始数据加载完成
    loading.value = false;
  }
}

// 获取博客详情
const contentData = ref<BlogContent>({});
const renderedContent = ref<string>('');

const getDetailData = async (id: number) => {
  contentLoading.value = true;
  try {
    const res = await getdetail(id);
    if (res.code === 200) {
      contentData.value = res.data;
      if (contentData.value.content) {
        renderedContent.value = md.render(contentData.value.content);
      }
    }
  } catch (error) {
    console.error('Error fetching blog detail:', error);
  } finally {
    contentLoading.value = false;
  }
}


</script>


<style scoped lang="scss">
.blog-detail {
  width: 1200px;
  margin: 50px auto;
  display: flex;
  justify-content: space-between;
}

.blog-sidebar {
  width: 240px;
  font-family: 'Montserrat', 'Arial', sans-serif;
  color: #232323;
  font-size: 15px;
  margin-right: 20px;
}

.sidebar-section {
  margin-bottom: 28px;
}

.sidebar-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 15px;
  letter-spacing: 1px;
}

.sidebar-subtitle {
  font-size: 13px;
  font-weight: bold;
  letter-spacing: 1px;
  text-transform: uppercase;
  margin-bottom: 6px;
}

.sidebar-divider {
  border-bottom: 1px solid #787878;
  margin-bottom: 12px;
}

.sidebar-categories,
.sidebar-posts {
  list-style: none;
  padding: 0;
  margin: 0;
}


.sidebar-categories>li {
  margin-bottom: 8px;
  padding-left: 0;
  font-size: 15px;
  color: #222;
  cursor: pointer;
  transition: color 0.2s;
  display: flex;
  justify-content: space-between;
}

.sidebar-category-children {
  padding: 4px 0;
  padding-left: 20px;

  >li {
    // 显示一行溢出省略号
    white-space: nowrap;
    overflow: hidden;
    width: 200px;
    line-height: 40px;
    cursor: pointer;
    font-size: 13px;
  }
}

.sidebar-posts li {
  margin-bottom: 18px;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 10px;
}

.sidebar-posts li:last-child {
  border-bottom: none;
}

.post-title {
  font-size: 12px;
  margin-bottom: 10px;
  line-height: 1.5;
  color: #232323;
  cursor: pointer;
}

.post-title:hover {
  text-decoration: underline;
}

.post-date {
  font-size: 13px;
  color: #b3b3b3;
  margin-bottom: 2px;
}

.right-title {
  font-size: 24px;
  color: #232323;
  font-size: 26px;
  font-weight: 600;
  text-transform: capitalize;
}

.right-date {
  color: #999999;
  font-size: 12px;
  font-weight: 400;
  text-transform: capitalize;
  font-style: normal;
}

.right-header {
  font-size: 16px;
  margin-bottom: 40px;
  margin-top: 35px;
  background-color: rgb(250, 250, 250);
  padding: 35px;
  color: #3C3C3C;
  font-size: 16px;
}

.active {
  color: #000;
  text-decoration: underline;
}

:deep(.markdown-body) {
  margin-top: 20px;
  font-size: 16px;
  color: #3C3C3C;

  h1,
  h2,
  h3,
  h4,
  h5,
  h6 {
    margin-top: 24px;
    margin-bottom: 16px;
    font-weight: 600;
    line-height: 1.25;
  }

  h1 {
    font-size: 2em;
  }

  h2 {
    font-size: 1.5em;
  }

  h3 {
    font-size: 1.25em;
  }

  h4 {
    font-size: 1em;
  }

  p {
    margin-bottom: 16px;

  }

  img {
    max-width: 100%;
    height: auto;
    margin: 16px 0;
  }

  ul,
  ol {
    padding-left: 2em;
    margin-bottom: 16px;
  }

  li {
    margin: 0.25em 0;
  }

  blockquote {
    padding: 0 1em;
    color: #6a737d;
    border-left: 0.25em solid #dfe2e5;
    margin: 0 0 16px 0;
  }

  code {
    padding: 0.2em 0.4em;
    margin: 0;
    font-size: 85%;
    background-color: rgba(27, 31, 35, 0.05);
    border-radius: 3px;
  }

  pre {
    padding: 16px;
    overflow: auto;
    font-size: 85%;
    line-height: 1.45;
    background-color: #f6f8fa;
    border-radius: 3px;
    margin-bottom: 16px;
  }

  pre code {
    padding: 0;
    margin: 0;
    font-size: 100%;
    word-break: normal;
    white-space: pre;
    background: transparent;
    border: 0;
  }

  a {
    color: #0366d6;
    text-decoration: none;

    &:hover {
      text-decoration: underline;
    }
  }

  hr {
    height: 0.25em;
    padding: 0;
    margin: 24px 0;
    background-color: #e1e4e8;
    border: 0;
  }

  table {
    display: block;
    width: 100%;
    overflow: auto;
    margin-bottom: 16px;
    border-spacing: 0;
    border-collapse: collapse;
  }

  table th {
    font-weight: 600;
  }

  table th,
  table td {
    padding: 6px 13px;
    border: 1px solid #dfe2e5;
  }

  table tr {
    background-color: #fff;
    border-top: 1px solid #c6cbd1;

    &:nth-child(2n) {
      background-color: #f6f8fa;
    }
  }
}

// 响应式样式
@media (max-width: 1240px) {
  .blog-detail {
    width: 95%;
    padding: 0 20px;
  }

  .blog-content-skeleton {
    width: calc(100% - 260px);
  }
}

@media (max-width: 768px) {
  .blog-detail {
    flex-direction: column;
  }

  .blog-sidebar {
    width: 100%;
    margin-right: 0;
    margin-bottom: 40px;
  }
}

.right-content-skeleton {
  width: 100%;
  padding: 10px;
}
</style>